package com.sumainfor.wx.tenant.controller.alipay;

import com.sumainfor.common.Constants;
import com.sumainfor.common.alipayutils.AlipayUtil;
import com.sumainfor.common.alipayutils.MerUtil.Merchant;
import com.sumainfor.common.alipayutils.SignUtils;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.CompuUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.wx.tenant.dao.TctenTenantCouponsMapper;
import com.sumainfor.wx.tenant.dao.UtilsMapper;
import com.sumainfor.wx.tenant.feign.Zfeign.ZpcGmioFeign;
import com.sumainfor.wx.tenant.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.wx.tenant.feign.ZuulFeignClient;
import com.sumainfor.wx.tenant.service.WechatService;
import com.sumainfor.wx.tenant.service.impl.GmioFeign.TenantCouService;
import net.bytebuddy.asm.Advice;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.security.pkcs11.P11Util;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Meng
 * @ClassName PaySmartController
 * @date 2019/12/8 20:57
 * @description: TODO
 */
@Controller
@RequestMapping("/PaySmart")
public class PaySmartController {


    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    ZpcGmioFeign zpcGmioFeign;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    TctenTenantCouponsMapper tctenTenantCouponsMapper;

    @Autowired
    TenantCouService tenantCouService;

    @Autowired
    ZpcMktFeign zpcMktFeign;
    @Autowired
    ZuulFeignClient zuulFeignClient;
    @Autowired
    WechatService wechatService;



    public static final String NOTIFYURLZN ="http://47.96.150.97:7000/wechat/tenant/PaySmart/PaySmartComputed";//智能设备充值回调



    /**
     * 智能设备充值
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping("/PayTenSmart")
    public JsonResult PayTenSmart ( @RequestBody  Map<String,Object> params){

        //TenId,
        //HouId,
        //Identifier//智能设备编号
        //Intelligent
        //houInfoId.*
        //transAmt(充值金额)
        //PaId
        //CouId
        //支付类型prepayType(1微信 2支付宝)

        String Attestation ="";
        JsonResult result = new JsonResult();
        // 获取当前时间
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String orderDate = sdf.format(nowTime);//租赁顾问签约抄水电燃,抄表记录的时间默认一致,

        Map<String, Object> payMap = new HashMap<>();
        payMap.put("transAmt", (long) CompuUtils.mul(MapUtils.getDouble(params, "transAmt"), new Double("100")));//交易金额(分)
        payMap.put("commodityName", "智能设备充值");//商品名称
        payMap.put("commodityDesc","智能设备");//商品描述
        payMap.put("orderDate",orderDate);//订单日期
        payMap.put("orderNo", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) );//商户订单号

        //获取组可签约房子的房源编号
        JsonResult getHouCorIdResult = zpcMktFeign.getHouCorId(params);
        Map<String, Object> getHouCorId = (Map<String, Object>) getHouCorIdResult.get("result");
        getHouCorId.put("area_id", getHouCorId.get("CorId"));
        //获取签约房子归属的公司
        JsonResult getAreaidResult = zuulFeignClient.getAreaid(getHouCorId);
        Map<String, Object> getAreaid = (Map<String, Object>) getAreaidResult.get("result");

        if(MapUtils.getInteger(params,"prepayType")==1) {//表示微信支付
            //获取openid
            Map<String, Object> tenOpIdMAP = wechatService.getTenOpenId(params);
            payMap.put("openid", tenOpIdMAP.get("uopid"));//微信用户id



            payMap.put("merNo", Merchant.EWG_ORMERN);//机构商户号
            payMap.put("terMerNo", Merchant.EWG_TEMERN);//终端商户号
            payMap.put("subChnlMerNo", Merchant.EWG_WXSMGRN);//微信子商户号
            payMap.put("subMerName", Merchant.EWG_TEMGRMING);//终端商户号名称


//            if (getAreaid.get("name").toString().equals("上海唐巢投资有限公司")) {
//                //上海唐巢投资公司不用.合并到公租房
//                payMap.put("merNo", Merchant.GZF_ORMERN);//机构商户号
//                payMap.put("terMerNo", Merchant.GZF_TEMERN);//终端商户号
//                payMap.put("subChnlMerNo", Merchant.GZF_WXSMGRN);//微信子商户号
//                payMap.put("subMerName", Merchant.GZF_TEMGRMING);//终端商户号名称
//            } else if (getAreaid.get("name").toString().equals("上海唐巢公共租赁住房运营有限公司")) {
//                payMap.put("merNo", Merchant.GZF_ORMERN);//机构商户号
//                payMap.put("terMerNo", Merchant.GZF_TEMERN);//终端商户号
//                payMap.put("subChnlMerNo", Merchant.GZF_WXSMGRN);//微信子商户号
//                payMap.put("subMerName", Merchant.GZF_TEMGRMING);//终端商户号名称
//            } else if (getAreaid.get("name").toString().equals("昆山唐巢公寓管理有限公司")) {
//                payMap.put("merNo", Merchant.KS_ORMERN);//机构商户号
//                payMap.put("terMerNo", Merchant.KS_TEMERN);//终端商户号
//                payMap.put("subChnlMerNo", Merchant.KS_WXSMGRN);//微信子商户号
//                payMap.put("subMerName", Merchant.KS_TEMGRMING);//子商户号名称
//            }
            payMap.put("notifyUrl", NOTIFYURLZN);//微信支付异步通知地址
            Attestation = AlipayUtil.AliPayPublic(payMap);
        }else if(MapUtils.getInteger(params,"prepayType")==2){//支付宝支付


            payMap.put("merNo", Merchant.EWG_ORMERN);//机构商户号
            payMap.put("terMerNo", Merchant.EWG_TEMERN);//终端商户号
            payMap.put("subChnlMerNo", Merchant.EWG_ZFSMGRN);//支付宝子商户号
            payMap.put("subMerName", Merchant.EWG_TEMGRMING);//终端商户号名称
            payMap.put("storeId", "tangchao001");//终端商户号名称
            payMap.put("terminalId", "tangchao001");//终端商户号名称



//            if (getAreaid.get("name").toString().equals("上海唐巢投资有限公司")) {
//                //上海唐巢投资公司不用.合并到公租房
//                payMap.put("merNo", Merchant.GZF_ORMERN);//机构商户号
//                payMap.put("terMerNo", Merchant.GZF_TEMERN);//终端商户号
//                payMap.put("subChnlMerNo", Merchant.GZF_ZFSMGRN);//支付宝子商户号
//                payMap.put("subMerName", Merchant.GZF_TEMGRMING);//终端商户号名称
//                payMap.put("storeId", "tangchao001");//终端商户号名称
//                payMap.put("terminalId", "tangchao001");//终端商户号名称
//            } else if (getAreaid.get("name").toString().equals("上海唐巢公共租赁住房运营有限公司")) {
//                payMap.put("merNo", Merchant.GZF_ORMERN);//机构商户号
//                payMap.put("terMerNo", Merchant.GZF_TEMERN);//终端商户号
//                payMap.put("subChnlMerNo", Merchant.GZF_ZFSMGRN);//支付宝子商户号
//                payMap.put("subMerName", Merchant.GZF_TEMGRMING);//终端商户号名称
//                payMap.put("storeId", "tangchaoGZ001");//终端商户号名称
//                payMap.put("terminalId", "tangchaoGZ001");//终端商户号名称
//            } else if (getAreaid.get("name").toString().equals("昆山唐巢公寓管理有限公司")) {
//                payMap.put("merNo", Merchant.KS_ORMERN);//机构商户号
//                payMap.put("terMerNo", Merchant.KS_TEMERN);//终端商户号
//                payMap.put("subChnlMerNo", Merchant.KS_ZFSMGRN);//支付宝子商户号
//                payMap.put("subMerName", Merchant.KS_TEMGRMING);//子商户号名称
//                payMap.put("storeId", "kunshan001");//终端商户号名称
//                payMap.put("terminalId", "kunshan001");//终端商户号名称
//            }
            payMap.put("notifyUrl", NOTIFYURLZN);//微信支付异步通知地址
            Attestation = AlipayUtil.ZhiFuBaopublic(payMap);
        }

        Map<String, Object> weChatMap = new HashMap<>();
        weChatMap.put("prepayId", payMap.get("orderNo"));//支付订单号
        weChatMap.put("prepayType",params.get("prepayType"));//支付订单号
        weChatMap.put("SouType", 8);//智能电表充值
        weChatMap.put("SourcePaId",params.get("PaId"));//关联合同编号
        weChatMap.put("BiMoney",params.get("transAmt"));//充值金额
        weChatMap.put("CorId",params.get("CorId"));//
        weChatMap.put("TenId",params.get("TenId"));//租客编号
        weChatMap.put("HouId",params.get("HouId"));//房源编号
        weChatMap.put("HouInfoId",params.get("HouInfoId"));//房源详表编号
        weChatMap.put("Identifier", params.get("Identifier"));//智能电表编号
        weChatMap.put("Intelligent", params.get("Intelligent"));//智能电表类型0蜂电 1大华
        weChatMap.put("Coucode", params.get("CouId"));
        weChatMap.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        weChatMap.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonInsertParms(weChatMap);
        zpcGmioFeign.AddPayWechat(weChatMap);//保存本次订单号与账单编号之间的关系
        return result.put(Attestation);
    }

    /**
     * 充值成功
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping("/PaySmartComputed")
    public JsonResult PaySmartComputed(@RequestParam Map<String,Object> params){

        JsonResult result = new JsonResult();

        //获取当前时间
        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String GenerateTimeNow = sdf.format(nowTime);

//
//        StringBuffer buf = new StringBuffer();
//        for (String key : params.keySet()) {
//            buf.append(key).append("=").append((String) params.get(key)).append("&");
//        }
//        String signatureStr = buf.substring(0, buf.length() - 1);
//        boolean signFlag = false;
//        try {
//            signFlag = SignUtils.verferSignDatas(signatureStr);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        if (!signFlag) {
//            // System.out.println("验签失败");
//            return result.putFailed("验签失败");
//        } else {
//            System.out.println("验签成功");
            if (params.get("respCode").toString().equals("0000")) {//是支付成功的操作

                //修改账单状态,增加支付信息。orderNo//订单编号
                params.put("prepayId", params.get("orderNo"));//本次支付订单号
                JsonResult getBillPayResult = zpcGmioFeign.getBillPay(params);
                List<Map<String, Object>> getBillPayMapList = (List<Map<String, Object>>) getBillPayResult.get("result");//根据订单信息查询关联账单
                for (Map<String, Object> getBillPayMap : getBillPayMapList) {
                    if (MapUtils.getInteger(getBillPayMap, "IsBill") == 0){//本次支付没有生成账单
                //修改本次支付成功的订单为已生成账单
                 zpcGmioFeign.UpdateWechat(params);
                //Map<String,Object> billMap  = new HashMap<>();
                //增加本次支付信息
                String BiIdUUID = "";//支付订单号
                    //获取账单编号
                    Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_tenant_bill");
                    }});
                    if (BiIduuid != null) {
                        int number = Integer.valueOf(BiIduuid.get("uuid").toString());
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("ZNCZ", number);

                    } else {
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("ZNCZ", 0);
                    }

                    //增加本次支付信息
                    String PayIdUUID = "";//支付订单号
                    //获取账单编号
                    Map<String, Object> payIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "PayId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_bill_pay");
                    }});
                    if (payIduuid != null) {
                        int number = Integer.valueOf(payIduuid.get("uuid").toString());
                        PayIdUUID = ComUtils.getLocalTrmSeqNum("ZF", number);

                    } else {
                        PayIdUUID = ComUtils.getLocalTrmSeqNum("ZF", 0);
                    }

                    Map<String, Object> billMap = new HashMap<>();
                        billMap.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                        billMap.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(billMap);
                    billMap.put("BiId", BiIdUUID);//账单编号
                    billMap.put("CorId", getBillPayMap.get("CorId"));//账单归属公司
                    billMap.put("BiName", "智能电表充值");//账单名称
                    billMap.put("IfTemporary", 0);//是否是临时账单0否 1 是
                    billMap.put("BiType", 8);//账单类型 8智能充值
                    billMap.put("Source", getBillPayMap.get("SourcePaId"));//账单来源,关联合同编号
                    billMap.put("BiMoney", getBillPayMap.get("BiMoney"));//账单金额,每个租客本次抄表需支付金额
                    billMap.put("BillExplain", getBillPayMap.get("Identifier"));//账单金额说明
                    billMap.put("BiGenerated", billMap.get("instm"));//账单生成日
                    billMap.put("EndTime", billMap.get("instm"));//账单结束日
                    billMap.put("LateDay", billMap.get("instm"));//账单最晚付款日
                    billMap.put("TenId", getBillPayMap.get("TenId"));//租客编号
                    billMap.put("HouId", getBillPayMap.get("HouId"));//房源编号
                    billMap.put("HouInfoId", getBillPayMap.get("HouInfoId"));//房源详表编号
                    billMap.put("CreateType", 1);//账单创建人类型1系统 2 人为
                    billMap.put("ExpTime", billMap.get("instm"));//逾期开始时间
                    billMap.put("PayId",PayIdUUID);//支付信息编号
                    billMap.put("Status", 2);//2支付成功
                    zpcGmioFeign.addTenantBill(billMap);

                    Map<String, Object> AddPayWechat = new HashMap<String, Object>();
                    AddPayWechat.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    AddPayWechat.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(AddPayWechat);

                    AddPayWechat.put("PayId", PayIdUUID);//支付信息编号
                    AddPayWechat.put("TenId", billMap.get("TenId"));//用户编号
                    AddPayWechat.put("Shape", "0");//支付形式   0.线上   1.线下
                    AddPayWechat.put("PayMode", getBillPayMap.get("prepayType"));//支付方式  1.微信  2.支付宝  3 银联支付
                    AddPayWechat.put("TransactionId", params.get("orderNo"));//微信支付订单号	该字段只有线上微信支付才有
                    AddPayWechat.put("PayTime", GenerateTimeNow);//支付时间
                    AddPayWechat.put("BiMoney", billMap.get("BiMoney"));//本次账单金额
                    AddPayWechat.put("PatStats", "2");//支付状态    1.未支付  2.支付成功
                    AddPayWechat.put("PayMoney", billMap.get("BiMoney"));//支付金额
                    if (FieldCheckUtil.isMapFieldNotNull(getBillPayMap, new String[]{"Coucode"})) {
                        Map<String, Object> getTenantCouCount = tctenTenantCouponsMapper.getTenantCouCount(new HashMap<String, Object>() {{
                            put("CouId", getBillPayMap.get("Coucode"));
                            put("TenId", getBillPayMap.get("TenId"));
                        }});

                        //优惠券大于0
                        if (MapUtils.isNotEmpty(getTenantCouCount)) {
                            Map<String, Object> cou = new HashMap<String, Object>();
                            cou.put("CouId", getBillPayMap.get("Coucode"));
                            cou.put("TenId", getBillPayMap.get("TenId"));
                            //修改优惠券已使用
                            tenantCouService.UpdateTenantCou(cou);
                            AddPayWechat.put("Couponcd", getBillPayMap.get("Coucode"));//优惠券编号
                            AddPayWechat.put("Couponamt", getTenantCouCount.get("Facevalue"));//优惠券金额
                            AddPayWechat.put("PayMoney", CompuUtils.reduce(MapUtils.getDouble(getBillPayMap, "BiMoney"), MapUtils.getDouble(getTenantCouCount, "Facevalue")));//优惠券金额
                        }
                    }
                    zpcGmioFeign.AddBillPay(AddPayWechat);
                    params.put("Intelligent", getBillPayMap.get("Intelligent"));//智能设备类型0蜂电 1大华
                    List<Map<String, Object>> InteDeviceBeeList = new ArrayList<>();
                    Map<String, Object> zhinengceshi = new HashMap<>();
                    zhinengceshi.put("Identifier", getBillPayMap.get("Identifier"));
                    InteDeviceBeeList.add(zhinengceshi);
                    //给智能设备充值
                    //传入参数  智能设备编号，智能设备类型
                    // InteDeviceBeeList 。Intelligent
                    if (params.get("Intelligent").toString().equals("0")) {
                        String InteDeviceBeeToken = redisUtils.get("InteDeviceBeeToken");
                        System.out.println(InteDeviceBeeToken);
                        //如果获取不到就重新登录
                        if (InteDeviceBeeToken == null) {
                            Map<String, Object> loginMap = new HashMap<String, Object>();
                            loginMap.put("version", UUIDUtils.generateShortUuid());//业务流水号UUID
                            loginMap.put("appid", InteDeviceBeeConfig.APP_ID);
                            //登录获取token
                            loginMap = InteDeviceBeeUtil.userLogin(InteDeviceBeeConfig.USERID, InteDeviceBeeConfig.PASS, loginMap);
                            if (loginMap.get("Code").toString().equals("0")) {//0 状态码 请求成功
                                InteDeviceBeeToken = loginMap.get("Expand").toString();
                                //token存到redis中 蜂电token 有效时长一小时
                                redisUtils.set("InteDeviceBeeToken", InteDeviceBeeToken, 3600);
                                System.out.println(InteDeviceBeeToken);
                            } else {
                                return result.putFailed("token获取失败");
                            }
                        }
                        //智能电表必定是每个房间都有一个电表，用房间集合的长度初始化智能电表设备编号数组
                        List<String> InteList = new ArrayList<String>();
                        Map<String, Object> headMap = new HashMap<String, Object>();
                        headMap.put("uid", InteDeviceBeeConfig.UID);//唐巢在蜂电用户ID
                        headMap.put("token", InteDeviceBeeToken);//访问令牌
                        headMap.put("version", "0116010101");//版本号默认0116010101
                        for (int i = 0; i < InteDeviceBeeList.size(); i++) {
                            Map<String, Object> mapce = InteDeviceBeeList.get(i);
                            if (mapce.get("Identifier") != null) {
                                InteList.add(mapce.get("Identifier").toString());
                            }
                        }

                        System.out.println("查询电表的list" + InteList);

                        //蜂电返回的参数
                        Map<String, Object> InteDataMap = InteDeviceBeeUtil.deviceAmmeterPcode(InteList, headMap);
                        System.out.println("返回成功的接口" + InteDataMap);
                        if (InteDataMap.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                            //电表数组
                            List<Map<String, Object>> InteDataList = (List<Map<String, Object>>) InteDataMap.get("Data");
                            for (Map<String, Object> mapOne : InteDeviceBeeList) {
                                if (mapOne.get("Identifier") != null) {
                                    for (Map<String, Object> mapTwo : InteDataList) {
                                        if (mapTwo.get("Ccode") != null) {
                                            if (mapOne.get("Identifier").toString().equals(mapTwo.get("Pcode").toString())) {
                                                mapOne.put("Uuid", mapTwo.get("Uuid"));
                                                System.out.println(mapOne);
                                            }
                                        }
                                    }
                                }
                            }

                            for (Map<String, Object> mapThree : InteDeviceBeeList) {
                                Map<String, Object> InteDataMaps = InteDeviceBeeUtil.accountRechargej(mapThree.get("Uuid").toString(), AddPayWechat.get("PayMoney").toString(), headMap);
                                if (!InteDataMaps.get("Code").toString().equals("0")) {
                                    return result.putFailed("蜂电充值失败");
                                }
                            }

                        } else {
                            return result.putFailed("第三方服务器繁忙");
                        }
                    } else if (params.get("Intelligent").toString().equals("1")) {//大华

                        String InteDaHuaToken = redisUtils.get("InteDaHuaToken");
                        //如果获取不到就重新登录
                        if (InteDaHuaToken == null) {
                            /*获取token*/
                            Map<String, Object> DaParams = new HashMap<String, Object>();
                            DaParams.put("pw", InteDeviceDaHuaConfig.PW);
                            DaParams.put("userName", InteDeviceDaHuaConfig.USERNAME);
                            DaParams = InteDeviceDaHuaUtil.getToken(DaParams);
                            if (DaParams.get("code") != null && DaParams.get("code").toString().equals("1")) {//1 状态码 请求成功
                                InteDaHuaToken = DaParams.get("data").toString();
                                //token有效期2个小时，所有接口Code=0 ，token失效 需要重新获取
                                redisUtils.set("InteDaHuaToken", InteDaHuaToken, 3600 * 2);
                                System.out.println(InteDaHuaToken);
                            } else {
                                return result.putFailed("token获取失败");
                            }
                        }

                        for (Map<String, Object> mapOne : InteDeviceBeeList) {
                            Map<String, Object> tokenMap = new HashMap<>();
                            tokenMap.put("token", InteDaHuaToken);
                            tokenMap.put("meter_id", mapOne.get("Identifier"));
                            tokenMap.put("amount", MapUtils.getInteger(AddPayWechat, "PayMoney"));
                            tokenMap.put("tra_id", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
                            //  Map<String, Object> getParams = InteDeviceDaHuaUtil.getRemainById(tokenMap);
                            Map<String, Object> payAmountByIdMap = InteDeviceDaHuaUtil.payAmountById(tokenMap);
                            if (!(payAmountByIdMap.get("code") != null && payAmountByIdMap.get("code").toString().equals("1"))) {//0 状态码 请求成功

                                return result.putFailed("大华充值失败");
                            }
                        }

                    }

                }
                }

               result.putSuccess("支付成功");
            }

            return result.putSuccess("支付成功");

        }


  //  }
}
